//常用业务方法
import store from '@/store'
import {router} from '@/router/router.js'
import $http from '@/utils/http/api.js'
import $ShowToast from '@/components/ch-toast/ch-showtotast.js'
import $Downguide from '@/components/ch-appdown/ch-downguide.js'
import CONFIG from '@/config'

/**
 * @description 彩虹体育常用方法封装对象
 */
const caihongsport = {
	config: CONFIG, //基础配置对象
	defaultUserAvatar: require('@/public/images/public/user_avatar.png'), //默认用户头像
	defaultBarAvatar: require('@/public/images/public/bar_avatar.png'), //默认球吧logo
	defaultExpertAvatar: require('@/public/images/public/expert_avatar.png'), //默认专家头像
	weekStr: ['周一','周二','周三','周四','周五','周六','周日'], //文字版周几
	/**
	 * @description 关注专家
	 * @param {string} commonId - 专家ID
	 * @return {boolean} 是否关注成功
	 */
	favExpert: (commonId) => {
		return new Promise((resolve,reject)=>{
			$http.post({
				url: '/api/appUser/careUserFollow',
				data: {
					commonId,
					type: 2,
					userId: store.state.user.userId,
				},
			}).then(data => {
				console.log(data);
				if(data.success){
					//数据同步
					store.commit('IS_FOLLOW_EXPERT', commonId)
					//成功提示
					$ShowToast({text: '已关注'})
					/*
					setTimeout(()=>{
						//进入私信
						let params = {cid: 'C2C' + commonId}
						router.push({ name: 'chatbox', params})
					}, 1000)
					*/
					//成功返回数据
					resolve(true)
				}else{
					uni.showToast({
						title: data.message,
						icon: 'error'
					})
					reject(false)
				}
			}).catch((err) => {
				console.log(err);
				uni.showToast({
					title: err.data.message || '关注操作失败',
					icon: 'none'
				})
				reject(false)
			})
		})
	},
	/**
	 * @description 关注比赛
	 * @param {string|number} commonId - 比赛ID
	 * @param {string|number} sportId - 比赛类型
	 * @param {string} remindTime - 提醒时间
	 * @return {boolean} 是否关注成功
	 */
	favMatch: (commonId, sportId, remindTime) => {
		return new Promise((resolve,reject)=>{
			$http.post({
				url: '/api/appUser/careUserFollow',
				data: {
					commonId,
					remindTime,
					sportId,
					type: 3,
					userId: store.state.user.userId,
				},
			}).then(data => {
				console.log(data);
				if(data.success){
					let match = {
						sportId,
						matchId: commonId
					}
					store.commit('IS_FOLLOW_MATCH', match)
					$ShowToast({text: '已收藏'})
					resolve(true)
				}else{
					uni.showToast({
						title: data.message,
						icon: 'error'
					})
					reject(false)
				}
			}).catch((err) => {
				console.log(err);
				uni.showToast({
					title: err.data.message || '收藏操作失败',
					icon: 'none'
				})
				reject(false)
			})
		})
	},
	/**
	 * @description 检查用户权限
	 * @param {number} actionType - 操作类型：[1|2|3|4|5]
	 *  @value 1：浏览点赞
	 *  @value 2：评论回复
	 *  @value 3：发布讨论
	 *  @value 4：发布免费方案
	 *  @value 5：申请UGC
	 * @return {boolean} 是否有权限操作
	 */
	checkUserLimit: (actionType) => {
		return new Promise((resolve,reject)=>{
			$http.get({
				url: '/api/appUser/user/score',
				data: {
					userId: store.state.user.userId
				},
			}).then(data => {
				console.log(data);
				if(data.success && data.result){
					if(data.result.type >= actionType){
						resolve(true)
					}else{
						resolve(false)
					}
				}else{
					console.log(data.message);
					uni.showToast({
						title: data.message || '数据加载异常，请稍后重试',
						icon: 'none'
					})
					reject(data)
				}
			}).catch((err) => {
				console.log(err);
				reject(err)
			})
		})
	},
	/**
	 * @description 保存访问日志
	 * @param {string} fromIndex - 来源页名称
	 * @param {string} toIndex - 访问页名称
	 * @return {boolean} 是否成功
	 */
	saveVisitLog: (fromIndex, toIndex) => {
		console.log('提交访问日志记录', fromIndex + '=>' + toIndex);
		return new Promise((resolve,reject)=>{
			$http.post({
				url: '/api/operate/record/add',
				data: {
					fromIndex,
					toIndex
				},
				noLoading: true,
				noCheck: true
			}).then(data => {
				console.log(data,'操作记录');
				if(data.success){
					resolve(true)
				}else{
					reject(data)
				}
			}).catch((err) => {
				console.log(err);
				reject(err)
			})
		})
	},
	/**
	 * @description 聊天记录时间转化
	 * @param {number} timestamp - 时间戳(秒)
	 * @return {string} 格式化后的时间
	 */
	dateFormat(timestamp) {
	    var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
	    var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数
	
	    var curDate = new Date( curTimestamp * 1000 ); // 当前时间日期对象
	    var tmDate = new Date( timestamp * 1000 );  // 参数时间戳转换成的日期对象
	
	    var Y = tmDate.getFullYear(), m = tmDate.getMonth() + 1, d = tmDate.getDate();
	    var H = tmDate.getHours(), i = tmDate.getMinutes(), s = tmDate.getSeconds();
	
	     if ( curDate.getFullYear() == Y && curDate.getMonth()+1 == m && curDate.getDate() == d ) {
	        return H.toString().padStart(2, '0') +':'+ i.toString().padStart(2, '0')
	    } else {
	        var newDate = new Date( (curTimestamp - 86400) * 1000 ); // 参数中的时间戳加一天转换成的日期对象
	        if ( newDate.getFullYear() == Y && newDate.getMonth()+1 == m && newDate.getDate() == d ) {
	            return '昨天'
	        } else if ( curDate.getFullYear() == Y ) {
				return m.toString().padStart(2, '0') + '.' + d.toString().padStart(2, '0')
	        } else {
	            return  Y + '.' + m.toString().padStart(2, '0') + '.' + d.toString().padStart(2, '0')
	        }
	    }
	},
	/**
	 * @description 获取邀请信息
	 * @return {object} 包含邀请码和邀请类型的对象
	 */
	getInviteCode(){
		let inviteCode = sessionStorage.getItem('inviteCode') || null;
		let inviteType = sessionStorage.getItem('inviteType') || null;
		if(inviteCode){
			//兼容旧版本
			if(!inviteType){
				inviteType = inviteCode.length == 7 ? 'expert' : 'user'
			}
			//返回邀请码
			return {inviteCode, inviteType};
		}else{
			return {};
		}
	},
	/**
	 * @description 获取回跳信息
	 * @return {object} 包含回跳页面别名和参数的对象
	 */
	getRedirectTo(){
		let redirectTo = sessionStorage.getItem('redirectTo');
		console.log(redirectTo,'redirectTo')
		if(redirectTo){
			try{
				redirectTo = JSON.parse(redirectTo);
				return redirectTo;
			}catch(e){
				//TODO handle the exception
				return null;
			}
		}else{
			return null;
		}
	},
	/**
	 * @description 发送短信验证码
	 * @param {object} 参数对象
	 *  @property {number} phone - 手机号
	 *  @property {string} term - 用户类型
	 *  @property {number} type - 0.登录模板 1.注册模板 2.忘记密码模板
	 * @return {boolean} 是否发送成功
	 */
	sendSmsCode({phone, term, type}){
		return new Promise((resolve,reject)=>{
			$http.get({
				url: '/api/sms', //短信发送接口
				data:{
					phone,
					term,
					type //0 .登录模板、1.注册模板、2.忘记密码模板
				}
			}).then((data)=>{
				if(data.code != 401 && data.success){
					uni.showToast({
						title: '验证码已发送',
						icon: 'none'
					})
					uni.setStorageSync('user_phone', phone)
					resolve(true)
				}else{
					reject(false)
					uni.showModal({
						title: '发送提示',
						content: data.message || '验证码发送失败，请稍后重试',
						showCancel: false
					})
				}
			}).catch((err)=>{
				console.log(err);
				reject(false)
				uni.showToast({
					title: '验证码发送失败，请稍后重试',
					icon: 'none'
				})
			})
		})
	},
	/**
	 * @description 跳转登录页面
	 */
	goUserLogin() {
		console.log(store.state.weixin,'store.state.weixin')
		let to = router.currentRoute
		let redirectTo = {name: to.name, params: to.query}
		//记录当前页面及参数
		sessionStorage.setItem('redirectTo', JSON.stringify(redirectTo))
		if(to.query.inviteCode){//邀请码
			if(!to.query.inviteType){//邀请类型
				to.query.inviteType = to.query.inviteCode.length == 7 ? 'expert' : 'user'
			}
			//携带邀请码
			let path = '/user/login/'+Date.now()+'?inviteType='+to.query.inviteType+'&inviteCode=' + to.query.inviteCode
			if(store.state.weixin){
				// let random = this.$CHS.randomString(10) + Date.now()
				// this.$goByName('weixinlogin', {random})
				router.push({ name: 'weixinlogin', params: {random: Date.now()} })
			}else{
				router.push({ path })
			}
		}else{
			// router.push({ name: 'userlogin', params: {random: Date.now()} })
			if(store.state.weixin){
				// let random = this.$CHS.randomString(10) + Date.now()
				// this.$goByName('weixinlogin', {random})
				router.push({ name: 'weixinlogin', params: {random: Date.now()} })
			}else{
				router.push({ name: 'userlogin', params: {random: Date.now()} })
			}
		}
	},
	/**
	 * @description 进入专家/用户主页
	 * @param {string} expertId - 专家/用户ID
	 * @param {string} userType - 类型：[expert|user]
	 *  @value expert：平台专家
	 *  @value user：平台用户
	 * @param {number} fromType - 触发跳转时的内容类型：[1|2|6|7|99]
	 *  @value 1：专家方案
	 *  @value 2：专家晒单
	 *  @value 6：话题贴
	 *  @value 7：投票贴
	 *  @value 99：用户方案
	 */
	goExpertHome(expertId, userType = 'expert', fromType = 1) {
		let pages = getCurrentPages() //页面栈
		if(userType === 'user'){
			//根据来源自动切换主页Tab
			let tabCur = 0 //方案
			if(fromType == 6 || fromType == 7){ 
				tabCur = 1 //话题
			}
			let index = pages.findIndex(page => {
				if(page.route.includes('MemberHome') && page.userId == expertId){
					return true;
				}
			})
			if(index > -1){//页面已打开时直接返回
				router.back(pages.length - 1 - index)
				pages[index].tabChange(tabCur) //切换页面tab
			}else{
				let params = {userId: expertId, tabCur}
				if(pages.length < 8){
					router.push({name: 'memberhome', params})
				}else{
					router.replace({name: 'memberhome', params})
				}
			}
		}else{
			//根据来源自动切换专家主页Tab
			let tabCur = 0 //方案
			if(fromType == 6 || fromType == 7){
				tabCur = 2 //话题
			}else if(fromType == 2){
				tabCur = 3 //晒单
			}
			let index = pages.findIndex(page => {
				if(page.route.includes('ExpertHome') && page.expertId == expertId){
					return true;
				}
			})
			if(index > -1){//页面已打开时直接返回
				router.back(pages.length - 1 - index)
				pages[index].tabChange(tabCur) //切换页面tab
			}else{
				let params = {eid: expertId, random: Date.now(), tabCur}
				if(pages.length < 8){
					router.push({name: 'experthome', params})
				}else{
					router.replace({name: 'experthome', params})
				}
			}
		}
	},
	/**
	 * @description 进入料详情
	 * @param {string} id - 方案ID
	 * @param {object} [param] - 页面参数
	 */
	goArticleDetail(id, param = {}) {
		console.log(id,param,'id,param')
		let pages = getCurrentPages()
		let params = {aid: id, random: Date.now(), ...param}
		if(pages.length < 8){
			router.push({name: 'articledetail', params})
		}else{
			router.replace({name: 'articledetail', params})
		}	
	},
	/**
	 * @description 进入动态详情
	 * @param {string} id - 动态ID
	 */
	goDynamicDetail(id) {
		let pages = getCurrentPages()
		let params = {did: id}
		if(pages.length < 8){
			router.push({name: 'dynamicdetail', params})
		}else{
			router.replace({name: 'dynamicdetail', params})
		}
	},
	/**
	 * @description 进入晒单详情
	 * @param {string} id - 晒单ID
	 * @param {object} [param] - 页面参数
	 */
	goShareDetail(id, param = {type: 'expert'}) {
		let pages = getCurrentPages()
		let params = {did: id, ...param}
		if(pages.length < 8){
			router.push({name: 'sharedetail', params})
		}else{
			router.replace({name: 'sharedetail', params})
		}
	},
	/**
	 * @description 进入讨论贴详情
	 * @param {string} id - 讨论贴ID
	 * @param {object} [param] - 页面参数
	 */
	goDiscussDetail(id, param = {}) {
		let pages = getCurrentPages()
		let params = {did: id, ...param}
		if(pages.length < 8){
			router.push({name: 'discussdetail', params})
		}else{
			router.replace({name: 'discussdetail', params})
		}
	},
	/**
	 * @description 进入资讯详情
	 * @param {string} id - 资讯ID
	 */
	goNewsDetail(id) {
		let pages = getCurrentPages()
		let params = {did: id}
		if(pages.length < 8){
			router.push({name: 'newsdetail', params})
		}else{
			router.replace({name: 'newsdetail', params})
		}
	},
	/**
	 * @description 进入比赛详情
	 * @param {object} match - 比赛对象
	 *  @property {number} matchId：比赛ID
	 *  @property {number} sportId：比赛类型
	 */
	goMatchDetail(match) {
		let params = {mid: match.matchId, sportId: match.sportId}
		if(match.sportId == 1){
			var name = 'matchfoot'
		}else{
			var name = 'matchbasket'
		}
		let pages = getCurrentPages()
		if(pages.length < 8){
			router.push({ name, params })
		}else{
			router.replace({ name, params })
		}
	},
	/**
	 * @description 进入球吧主页
	 * @param {object} barId 球吧ID
	 * @param {object} [deny] 是否禁止：[0|1]
	 */
	goBarHome(barId, deny) {
		if(deny === 1){
			$ShowToast({text: '您已被移出球吧，不能访问此球吧', type: 2, time: 3})
		}else{
			let pages = getCurrentPages()
			let index = pages.findIndex(page => {
				if(page.route.includes('BallbarHome') && page.barId == barId){
					return true;
				}
			})
			if(index > -1){
				router.back(pages.length - 1 - index)
			}else{
				let params = {bid: barId}
				if(pages.length < 8){
					router.push({name: 'barhome', params})
				}else{
					router.replace({name: 'barhome', params})
				}
			}
		}
	},
	/**
	 * @description 进入用户协议等页面
	 * @param {string} page 协议页面别名：[service|privacy|recharge|child|guide|growth]
	 *  @value service：用户服务协议
	 *  @value privacy：用户隐私协议
	 *  @value recharge：用户充值协议
	 *  @value child：儿童保护协议
	 *  @value guide：用户使用手册
	 *  @value growth：会员权益说明
	 */
	goAbout(page) {
		let params = {name: page}
		let pages = getCurrentPages()
		if(pages.length < 10){//处理极限情况下页面栈超出问题
			router.push({ name: 'agreement', params })
		}else{
			router.replace({ name: 'agreement', params })
		}
	},
	/**
	 * @description 专家私信
	 * @param {string} expertId - 专家ID
	 * @param {number} [userIdentity] - 专家类型：[1|2]
	 *  @value 1：自有专家
	 *  @value 2：UGC专家
	 */
	goChat(expertId, userIdentity) {
		if(userIdentity != 1){ //非自有专家禁止私信
			$ShowToast({text: '该专家未开通聊天功能', type: 2})
			return
		}
		let params = {cid: 'C2C' + expertId}
		router.push({ name: 'chatbox', params})
	},
	/**
	 * @description 进入充值页面
	 * @param {object} [redirect] - 回跳页面信息对象
	 */
	goRecharge(redirect = {}){
		//保存买料、打赏、购卡来源时的跳转地址
		uni.setStorageSync('recharge_redirect', redirect)
		router.push({name: 'userrecharge'})
	},
	/**
	 * @description 充值成功返回
	 * @param {boolean} goRechargePage - 是否返回充值页面
	 */
	rechargeSuccess(goRechargePage) {
		//存在买料、打赏、购卡来源时需回跳
		let redirect = uni.getStorageSync('recharge_redirect')
		if(redirect && redirect.type) {
			uni.removeStorageSync('recharge_redirect')
			let params = {
				random: Date.now() 
			}
			if(redirect.type == 'article'){ //回跳料详情页面
				params.aid = redirect.id
				router.replace({name: 'articledetail', params})
				return
			}else if(redirect.type == 'expert'){ //回跳专家打赏页面
				params.eid = redirect.id
				router.replace({name: 'experthome', params})
				return
			}else if(redirect.type == 'card'){ //回跳专家优享卡页面
				params.eid = redirect.id
				router.replace({name: 'expertcards', params})
				return
			}else if(redirect.type == 'numcard'){ //回跳专家次卡页面
				params.eid = redirect.id
				router.replace({name: 'expertnumcard', params})
				return
			}
		}
		if(goRechargePage){
			//充值成功跳转充值页面
			router.replace({name: 'userrecharge', params: {success: 1}})
		}
	},
	/**
	 * @description 过滤iOS端发布的富文本内容
	 * @param {string} content - 需处理的富文本内容
	 * @return {string} 返回富文本内容
	 */
	filterRichText(content) {
		if(content && content.includes('<body>') && content.includes('</body>')){
			let html = content.match(/<body>[\s\S]*<\/body>/ig)
			if(html){
				html = html[0].slice(6, -7).trim()
				/* if(/<\/span>/ig.test(html)){
					html = html.replace(/<span.*?>/ig, "");
					html = html.replace(/<\/span>/ig, "");
				} */
				return html
			}
		}
		return content
	},
	/**
	 * @description 获取七牛token
	 * @return {object} 返回包含token与域名的对象
	 */
	getQiniuToken() {
		return new Promise((resolve,reject)=>{
			$http.post({
				url: '/api/getToken',
			}).then(data => {
				console.log(data,'七牛');
				if(data.success && data.result){
					resolve(data.result)
				}else{
					reject(data)
				}
			}).catch((err) => {
				console.log(err)
				reject(err)
			})
		})
	},
	/**
	 * @description 错误请求处理
	 * @param {string} name - 错误后返回页面别名
	 * @param {string} message - 错误提示文字
	 */
	errorRequest(name, message) {
		uni.showModal({
			title: '错误提示',
			content: message,
			showCancel: false,
			success: (res) => {
				if(res.confirm){
					router.pushTab({name})
				}
			}
		})
	},
	/**
	 * @description 更新tabbar 
	 */
	updateTabbarIcon(){
		$http.get({
			url: '/api/icon/query',
			data:{
				code: 'tabbar'
			},
			noLoading: true,
			noCheck: true
		}).then((data)=>{
			console.log(data);
			if(data.success && data.result){
				// let tabList = ['home','info','message','match','my']
				let tabList = ['home','message','match','my']
				let items = Object.keys(data.result)
				if(items.length > 0){
					tabList.forEach((item, index)=>{
						let normal = item+'_normal'
						let select = item+'_select'
						if(data.result[normal] && data.result[select]){
							uni.setTabBarItem({
								index,
								iconPath: data.result[normal],
								selectedIconPath: data.result[select]
							})
						}
					})
				}
			}
		}).catch((err)=>{
			console.log(err);
		})
	},
	/**
	 * @description 查询优惠活动资格
	 * @param {string} userId 用户ID
	 */
	getCouponActivity(userId){
		$http.get({
			url: '/api/coupon/activity',
			data: {
				userId: userId || store.state.user.userId || ''
			}
		}).then(data => {
			console.log('activity', data);
			store.commit('UPDATE_USERINFO', { couponActivity: data.success ? data.result : false });
		}).catch(err => {
			console.log(err);
		})
	},
	/**
	 * @description 应用更新查询
	 */
	appUpdateCheck(){
		//此处需要接口返回最新版本号
		if(this.compareVersion(CONFIG.versionName, '2.0.0') < 0){
			if(router.currentRoute.path.indexOf('Pay') < 0){
				uni.showModal({
					title: '更新提示',
					content: '彩虹体育新版本已经准备好，是否现在进行更新？',
					success: (res) => {
						if (res.confirm) {
							window.location.replace(location.href)
						}
					}
				})
			}
		}
	},
	/**
	 * @description 版本号比较
	 * @param {string} v1 - 当前版本号
	 * @param {string} v2 - 新版本号
	 * @return {number} 返回当前版本是否是最新版本: -1 否；1 是；0 版本一致
	 */
	compareVersion(v1, v2) {
		v1 = v1.split('.')
		v2 = v2.split('.')
		const len = Math.max(v1.length, v2.length)
	
		while (v1.length < len) {
			v1.push('0')
		}
		while (v2.length < len) {
			v2.push('0')
		}
	
		for (let i = 0; i < len; i++) {
			const num1 = parseInt(v1[i])
			const num2 = parseInt(v2[i])
	
			if (num1 > num2) {
				return 1
			} else if (num1 < num2) {
				return -1
			}
		}
	
		return 0
	},
	/**
	 * @description 下载APP
	 */
	downApp(type){
		let ua = navigator.userAgent.toLowerCase();
		if (ua.match(/micromessenger/i) == "micromessenger"){
			$Downguide({show: true})
		}else{
			if(/(iphone|ipad|mac|ios)/i.test(navigator.userAgent) || type === 1){
				const ios_url = CONFIG.iosAppUrl
				location.href = ios_url
				//window.open(ios_url, "_blank")
			}else{
				const android_url = CONFIG.androidAppUrl
				location.href = android_url
				//window.open(android_url, "_blank")
			}
		}
	},
	/**
	 * @description 生成随机字符串
	 * @param {number} len - 随机字符串长度
	 * @return {string} 返回字符串
	 */
	randomString(len) {
		len = len || 32;
		var myChars = 'ABCDEFGHJKMNPQRSTWYZabcdefhijkmnprstwyz245678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
		var maxPos = myChars.length;
		var str = '';
		for (let i = 0; i < len; i++) {
			str += myChars.charAt(Math.floor(Math.random() * maxPos));
		}
		return str;
	},
	/**
	 * @description 引入原生JS
	 * @param {string} src - JS文件URL
	 */
	loadJs(src) {
		return new Promise((resolve,reject)=>{
			let script = document.createElement('script');
			script.type = "text/javascript";
			script.src= src;
			document.body.appendChild(script);
			
			script.onload = ()=>{
			  resolve();
			}
			script.onerror = ()=>{
			  reject();
			}
		})
	},
	/**
	 * @description 足球比赛状态
	 * @param {number} statusId - 状态编号
	 * @return {string} 返回比赛状态名称
	 */
	getMatchFootStatus(statusId) {
		switch (statusId){
			case 0:
				return '比赛异常' 
				break;
			case 1:
				return '未开赛' 
				break;
			case 2:
				return '上半场' 
				break;
			case 3:
				return '中场' 
				break;
			case 4:
				return '下半场' 
				break;
			case 5:
				return '加时赛' 
				break;
			case 6:
				return '加时赛(弃用)'
				break;
			case 7:
				return '点球决战' 
				break;
			case 8:
				return '完场' 
				break;
			case 9:
				return '推迟' 
				break;
			case 10:
				return '中断' 
				break;
			case 11:
				return '腰斩' 
				break;
			case 12:
				return '取消' 
				break;
			case 13:
				return '待定' 
				break;
			default:
				return '状态异常'
				break;
		}
	},
	/**
	 * @description 篮球比赛状态
	 * @param {number} statusId - 状态编号
	 * @return {string} 返回比赛状态名称
	 */
	getMatchBasketStatus(statusId) {
		switch (statusId){
			case 0:
				return '比赛异常' 
				break;
			case 1:
				return '未开赛' 
				break;
			case 2:
				return '第一节' 
				break;
			case 3:
				return '第一节完' 
				break;
			case 4:
				return '第二节' 
				break;
			case 5:
				return '第二节完' 
				break;
			case 6:
				return '第三节'
				break;
			case 7:
				return '第三节完' 
				break;
			case 8:
				return '第四节' 
				break;
			case 9:
				return '加时' 
				break;
			case 10:
				return '完场' 
				break;
			case 11:
				return '中断' 
				break;
			case 12:
				return '取消' 
				break;
			case 13:
				return '延期' 
				break;
			case 14:
				return '腰斩' 
				break;
			case 15:
				return '待定' 
				break;
			default:
				return '状态异常'
				break;
		}
	},
	//比赛技术统计名称足球
	getLiveFootStats(statusId) {
		switch (statusId){
			case 1:
				return '进球' 
				break;
			case 2:
				return '角球' 
				break;
			case 3:
				return '黄牌' 
				break;
			case 4:
				return '红牌' 
				break;
			case 5:
				return '越位' 
				break;
			case 6:
				return '任意球'
				break;
			case 7:
				return '球门球' 
				break;
			case 8:
				return '点球' 
				break;
			case 9:
				return '换人' 
				break;
			case 10:
				return '比赛开始' 
				break;
			case 11:
				return '中场' 
				break;
			case 12:
				return '结束' 
				break;
			case 13:
				return '半场比分' 
				break;
			case 14:
				return '半场比分' 
				break;
			case 15:
				return '两黄变红' 
				break;
			case 16:
				return '点球未进' 
				break;
			case 17:
				return '乌龙球' 
				break;
			case 18:
				return '助攻' 
				break;
			case 19:
				return '伤停补时' 
				break;
			case 20:
				return '伤停补时' 
				break;
			case 21:
				return '射正' 
				break;
			case 22:
				return '射偏' 
				break;
			case 23:
				return '进攻' 
				break;
			case 24:
				return '危险进攻' 
				break;
			case 25:
				return '控球率' 
				break;
			case 26:
				return '加时赛结束' 
				break;
			case 27:
				return '点球大战结束' 
				break;
			case 28:
				return 'VAR(视频助理裁判)' 
				break;
			case 29:
				return '点球(点球大战)' 
				break;
			case 30:
				return '点球未进(点球大战)' 
				break;
			default:
				return '其他'
				break;
		}
	},
	//比赛技术统计名称篮球
	getLiveBasketStats(statusId){
		switch (statusId){
			case 1:
				return '3分球进球数'
				break;
			case 2:
				return '2分球进球数'
				break;
			case 3:
				return '罚球进球数'
				break;
			case 4:
				return '剩余暂停数'
					break;
			case 5:
				return '犯规数'
				break;	
			case 6:
				return '罚球命中率'
				break;
			case 7:
				return '总暂停数'
				break;
			default:
				return '其他'
				break;
		}
	},
	//比赛事件原因
	getLiveReason(statusId) {
		switch (statusId){
			case 1:
				return '犯规' 
				break;
			case 2:
				return '个人犯规' 
				break;
			case 3:
				return '侵犯对手/受伤换人' 
				break;
			case 4:
				return '战术犯规/战术换人' 
				break;
			case 5:
				return '进攻犯规' 
				break;
			case 6:
				return '无球犯规'
				break;
			case 7:
				return '持续犯规' 
				break;
			case 8:
				return '持续侵犯' 
				break;
			case 9:
				return '暴力行为' 
				break;
			case 10:
				return '危险动作' 
				break;
			case 11:
				return '手球犯规' 
				break;
			case 12:
				return '严重犯规' 
				break;
			case 13:
				return '故意犯规' 
				break;
			case 14:
				return '阻挡进球机会' 
				break;
			case 15:
				return '拖延时间' 
				break;
			case 16:
				return '视频回看裁定' 
				break;
			case 17:
				return '判罚取消' 
				break;
			case 18:
				return '争论' 
				break;
			case 19:
				return '对判罚表达异议' 
				break;
			case 20:
				return '犯规和攻击言语' 
				break;
			case 21:
				return '过度庆祝' 
				break;
			case 22:
				return '没有回退到要求的距离' 
				break;
			case 23:
				return '打架' 
				break;
			case 24:
				return '辅助判罚' 
				break;
			case 25:
				return '替补席' 
				break;
			case 26:
				return '赛后行为' 
				break;
			case 27:
				return '其他原因' 
				break;
			case 28:
				return '未被允许进入场地' 
				break;
			case 29:
				return '进入比赛场地' 
				break;
			case 30:
				return '离开比赛赛场' 
				break;
			case 31:
				return '非体育道德行为' 
				break;
			case 32:
				return '非主观意愿的恶意犯规' 
				break;
			case 33:
				return '冒充或顶替' 
				break;
			case 34:
				return '干预var复审' 
				break;
			case 35:
				return '进入裁判评审区' 
				break;
			case 36:
				return '吐口水' 
				break;
			case 37:
				return '病毒' 
				break;
			default:
				return '未知'
				break;
		}
	},
	//VAR原因
	getLiveVarReason(statusId) {
		switch (statusId){
			case 0:
				return '其他'
				break;
			case 1:
				return '进球判定'
				break;
			case 2:
				return '进球未判定'
				break;
			case 3:
				return '点球判定'
				break;
			case 4:
				return '点球未判定'
					break;
			case 5:
				return '红牌判定'
				break;	
			case 6:
				return '出牌处罚判定'
				break;
			case 7:
				return '错认身份'
				break;
			default:
				return '其他'
				break;
		}
	},
	//VAR结果
	getLiveVarResult(statusId) {
		switch (statusId){
			case 0:
				return '未知'
				break;
			case 1:
				return '进球有效'
				break;
			case 2:
				return '进球无效'
				break;
			case 3:
				return '点球有效'
				break;
			case 4:
				return '点球取消'
				break;
			case 5:
				return '红牌有效'
				break;	
			case 6:
				return '红牌取消'
				break;
			case 7:
				return '出牌处罚核实'
				break;
			case 8:
				return '出牌处罚更改'
				break;	
			case 9:
				return '维持原判'
				break;
			case 10:
				return '判罚更改'
				break;
			default:
				return '其他'
				break;
		}
	},
	/**
	 * @description 篮球比赛计算总得分
	 * @param {string} socres - 分数统计
	 * @return {number} 返回总分数
	 */
	sumScoreBasket(socres){
		if(typeof socres == 'string'){
			socres = JSON.parse(socres)
		}
		return socres.reduce((item, sum) => {
			return item + sum;
		});
	},
	/**
	 * @description 足球比赛计算总得分
	 * @param {string} socres - 分数统计
	 * @return {number} 返回总分数
	 */
	sumScoreFoot(socres){
		if(typeof socres == 'string'){
			socres = JSON.parse(socres)
		}
		//return socres[5] ? socres[5] + socres[6] : socres[0] + socres[6]
		return socres[0]
	},
	/**
	 * @description 节流
	 * @param {function} fn - 回调方法
	 * @param {number} time - 间隔时间
	 */
	throttle: (fn, time) => {
		var timeout = null;
		return function() {
			if (timeout) {
				return;
			}
			timeout = setTimeout(() => {
				timeout = null;
				fn.call(this, arguments);
			}, time);
		};
	},
	/**
	 * @description 防抖
	 * @param {function} fn - 回调方法
	 * @param {number} time - 间隔时间
	 */
	debounce: (fn, time) => {
		var timeout = null;
		return function() {
			if( timeout !== null ){
				clearTimeout(timeout)
			}
			timeout = setTimeout(() => {
				fn.call(this, arguments);
			}, time);
		};
	},
	/**
	 * @description 获取服务器时间
	 * @return {number} 返回时间戳
	 */
	async getWebTime() {
		var [err, res] = await uni.request({
			url: '/api/index'
		});
		console.log(res,'res');
		if(res != null && res.data && res.data.timestamp){
			return res.data.timestamp
		}else{
			return Date.now()
		}
	},
	/**
	 * @description 获取当前日期
	 * @return {string} 返回当前年月日，格式：2023-07-22
	 */
	getNowDate() {
		let dd = new Date();
		let y = dd.getFullYear();
		let m = dd.getMonth()+1;//获取当前月份的日期 
		let d = dd.getDate();
		m = m.toString().padStart(2, '0')
		d = d.toString().padStart(2, '0')
		return y+'-'+m+'-'+d
	},
	/**
	 * @description 获取汉字周几
	 * @param {string} datetime - 日期时间，格式：2023-07-22 17:44:30
	 * @return {string} 返回周几
	 */
	getDateStr(datetime) {
		if(!datetime)
			return ''
		let weekDay = ['周日','周一','周二','周三','周四','周五','周六'];
		datetime = datetime.replace(/-/g, "/")
	    let dd = new Date(datetime); 
		let week = dd.getDay();
		return weekDay[week]
	},
	/**
	 * @description 转化比赛时间
	 * @param {number} value - 时间秒数
	 * @return {string}
	 */
	formatSeconds(value) {
	    var theTime = parseInt(value);// 秒
	    var minu= 0;// 分
	    var hour= 0;// 小时
	
	    if(theTime >= 60) {
	        minu= parseInt(theTime/60);
	        theTime = parseInt(theTime%60);
	        if(minu >= 60) {
	            hour= parseInt(minu/60);
	            minu= parseInt(minu%60);
	        }
	    }
	    var result = ""+parseInt(theTime) + "″";
	    if(minu > 0) {
	        result = ""+parseInt(minu)+"′"+result;
	    }
	    if(hour> 0) {
	        result = ""+parseInt(hour)+"-"+result;
	    }
	    return result;
	},
	/**
	 * @description 检测富文本中的文字字数
	 * @param {string} str - 富文本内容
	 * @return {number} 返回文字字数
	 */
	checkTextLength(str) {
		if(!str) return 0
		str = str
			.replace(/<[^<>]+>/g, "")
			.replace(/&nbsp;/gi, "");
		return str.length
	},
	/**
	 * @description 检查CDN文件路径
	 * @param {string} path - 文件路径
	 * @param {string} type - 文件类型：[video|image]
	 * @return {string}
	 */
	checkFilePath(path, type) {
		if(path.indexOf('http') > -1){
			return path
		}else{
			if(type == 'video'){
				return store.state.videoDomain + '/' + path
			}else{
				return store.state.imageDomain + '/' + path
			}
		}
	},
	/**
	 * @description 图片加载失败
	 * @param {object} event - 加载错误的事件对象
	 */
	imageLoadError(event) {
		console.log(event);
		if( event.target.tagName.toUpperCase() === 'IMG' ){
			event.target.src = require('@/public/images/public/error.png')
		}
	},
	/**
	 * @description 转化预测数据，后端数据 => 前端组件可用数据，用于料料详情展示（可能含专家预测）
	 * @param {Array<object>} items - 多个玩法的指数数据
	 * @param {number} finish - 结束状态，用于判断是否展示结果
	 * @return {object} 返回处理后的对象，包含不同玩法
	 */
	itemsToScores(items, finish){
		console.log(items,'items')
		let scores = {}
		items.forEach((item) => {
			item.zs = item.zs ? item.zs.split(',') : []
			item.finish = finish
			if(item.forecastResult){
				item.forecastResult = item.forecastResult.split(',')
			}
			if(item.forecastType == 'rqspf'){
				item.name = ['让球', '让胜', '让平', '让负']
				if(item.matchResult != null){
					if(item.matchResult == '0'){
						item.matchResult = [0,0,0,1]
					}
					if(item.matchResult == '1'){
						item.matchResult = [0,0,1,0]
					}
					if(item.matchResult == '3'){
						item.matchResult = [0,1,0,0]
					}
				}
				scores.rqspf = item
			}
			if(item.forecastType == 'rqsf'){
				item.name = ['主胜', '让球', '客胜']
				if(item.matchResult != null){
					if(item.matchResult == '0'){
						item.matchResult = [0,0,1]
					}
					if(item.matchResult == '1'){
						item.matchResult = [0,0,0]
					}
					if(item.matchResult == '3'){
						item.matchResult = [1,0,0]
					}
				}
				scores.rqsf = item
			}
			if(item.forecastType == 'spf'){
				item.name = ['胜', '平', '负']
				if(item.matchResult != null){
					if(item.matchResult == '0'){
						item.matchResult = [0,0,1]
					}
					if(item.matchResult == '1'){
						item.matchResult = [0,1,0]
					}
					if(item.matchResult == '3'){
						item.matchResult = [1,0,0]
					}
				}
				scores.spf = item
			}
			if(item.forecastType == 'jq'){
				item.name = ['0球', '1球', '2球','3球', '4球', '5球','6球', '7+球']
				scores.jq = item
			}
			if(item.forecastType == 'dxq'){
				item.name = ['大球', '即时数据', '小球']
				if(item.matchResult != null){
					item.matchResult = Number(item.matchResult)
					if(item.matchResult > item.zs[1]){
						item.matchResult = [1,0,0]
					}else if(item.matchResult < item.zs[1]){
						item.matchResult = [0,0,1]
					}else if(item.matchResult == item.zs[1]){
						item.matchResult = [0,0,0]
					}
				}
				console.log(item.matchResult);
				scores.dxq = item
			}
			if(item.forecastType == 'dxf'){
				item.name = ['大分', '即时数据', '小分']
				if(item.forecastResult){
					let result = Object.assign([], item.forecastResult)
					item.forecastResult[0] = result[1]
					item.forecastResult[1] = result[0]
				}
				if(item.matchResult != null){
					item.matchResult = Number(item.matchResult)
					if(item.matchResult > item.zs[0]){
						item.matchResult = [1,0,0]
					}else if(item.matchResult < item.zs[0]){
						item.matchResult = [0,0,1]
					}else if(item.matchResult == item.zs[0]){
						item.matchResult = [0,0,0]
					}
				}
				scores.dxf = item
			}
			if(item.forecastType == 'rfsf'){
				item.name = ['让分', '客胜', '主胜']
				if(item.forecastResult){
					if(item.forecastResult[2]=="1"){
						item.forecastResult=["0","1","0"]
					}else if(item.forecastResult[1]=="1"){
						item.forecastResult=["0","0","1"]
					}
				}
				if(item.matchResult != null){
					if(item.matchResult == '0'){
						item.matchResult = [0,1,0]
					}else if(item.matchResult == '3'){
						item.matchResult = [0,0,1]
					}else if(item.matchResult == '1'){
						item.matchResult = [0,0,0]
					}
				}
				scores.rfsf = item
			}
		})
		console.log(scores);
		return scores
	},
	/**
	 * @description 原始指数转化，接口数据 => 前端可用数据，用于料发布（不含专家预测）
	 * @param {object} item - 后端返回的指数对象
	 * @return {object} 返回处理后的对象，包含不同玩法
	 */
	zsToScores(item){
		let scores = {}
		if(item.jq){
			scores.jq = {
				name: ['0球', '1球', '2球','3球', '4球', '5球','6球', '7+球'],
				zs: item.jq.split(',')
			}
		}
		if(item.dxq){
			scores.dxq = {
				name: ['大球', '即时数据', '小球'],
				zs: item.dxq.split(',')
			}
		}
		if(item.dxf){
			scores.dxf = {
				name: ['大分', '即时数据', '小分'],
				zs: item.dxf.split(',')
			}
		}
		if(item.spf){
			scores.spf = {
				name: ['胜', '平', '负'],
				zs: item.spf.split(',')
			}
		}
		if(item.rqspf){
			scores.rqspf = {
				name: ['让球', '让胜', '让平', '让负'],
				zs: item.rqspf.split(',')
			}
		}
		if(item.rqsf){
			scores.rqsf = {
				name: ['主胜', '让球', '客胜'],
				zs: item.rqsf.split(',')
			}
		}
		if(item.rfsf){
			scores.rfsf = {
				name: ['让分', '客胜', '主胜'],
				zs: item.rfsf.split(',')
			}
			// scores.rfsf = {
			// 	name: ['让分', '主胜', '客胜'],
			// 	zs: item.rfsf.split(',')
			// }
		}
		console.log(scores);
		return scores
	},
	/**
	 * @description 转化预测数据，后端数据 => 前端编辑可用数据，用于料编辑回显（含专家预测）
	 * @param {Array<object>} forecast - 后端返回的多个玩法的预测数据
	 * @return {object} 返回处理后的对象，包含不同玩法
	 */
	forecastToScores(forecast){
		let scores = {}
		let items = JSON.parse(JSON.stringify(forecast)); //简单拷贝
		items.forEach((item) => {
			let actives = []
			item.zs = item.zs.split(',')
			if(item.forecastResult){
				item.forecastResult = item.forecastResult.split(',')
				if(item.forecastType == 'dxf'){
					let result = Object.assign([], item.forecastResult)
					item.forecastResult[0] = result[1]
					item.forecastResult[1] = result[0]
				}
				item.forecastResult.forEach((item, index) => {
					if(item == 1){
						actives.push(index)
					}
				})
			}
			if(item.forecastType == 'jq'){
				scores.jq = {
					name: ['0球', '1球', '2球','3球', '4球', '5球','6球', '7+球'],
					zs: item.zs,
					actives: actives
				}
			}
			if(item.forecastType == 'dxq'){
				scores.dxq = {
					name: ['大球', '即时数据', '小球'],
					zs: item.zs,
					actives: actives
				}
			}
			if(item.forecastType == 'dxf'){
				scores.dxf = {
					name: ['大分', '即时数据', '小分'],
					zs: item.zs,
					actives: actives
				}
			}
			if(item.forecastType == 'spf'){
				scores.spf = {
					name: ['胜', '平', '负'],
					zs: item.zs,
					actives: actives
				}
			}
			if(item.forecastType == 'rqspf'){	
				scores.rqspf = {
					name: ['让球', '让胜', '让平', '让负'],
					zs: item.zs,
					actives: actives
				}
			}
			if(item.forecastType == 'rqsf'){
				scores.rqsf = {
					name: ['主胜', '让球', '客胜'],
					zs: item.zs,
					actives: actives
				}
			}
			if(item.forecastType == 'rfsf'){
				if(actives[0]==2){
					actives[0]=1
				}else if(actives[0]==1){
					actives[0]=2
				}
				scores.rfsf = {
					name: ['让分', '客胜', '主胜'],
					zs: item.zs,
					actives: actives
				}
			}
		})
		console.log(scores);
		return scores
	}
}

export default caihongsport